package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UsernameExistServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");

            AccountService accountService = new AccountService();
            Account account = accountService.getAccount(username);

            // 设置响应的类型
            resp.setContentType("text/json");
            PrintWriter out = resp.getWriter();

        Result result1 = new Result();

            if(account == null){
                // 用户不存在，可以使用该用户名
                result1.setCode(0);
                result1.setMsg("Not Exist");
            }
            else{
                // 用户名已存在，无法使用该用户名
                result1.setCode(1);
                result1.setMsg("Exist");
            }

        String str = JSON.toJSONString(result1);
            out.print(str);
            //关闭流，释放资源
            out.flush();
            out.close();

    }
}
